package com.ruicar.afs.cloud.afscase.message.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseChannelInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseCustIndividual;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseCustInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.service.CaseChannelInfoService;
import com.ruicar.afs.cloud.afscase.infomanagement.service.CaseCustIndividualService;
import com.ruicar.afs.cloud.afscase.infomanagement.service.CaseCustInfoService;
import com.ruicar.afs.cloud.afscase.message.entity.MessageTemplate;
import com.ruicar.afs.cloud.afscase.message.mapper.MessageTemplateMapper;
import com.ruicar.afs.cloud.afscase.message.service.MessageTemplateService;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.*;
import com.ruicar.afs.cloud.message.sendmessage.config.MessageConfig;
import com.ruicar.afs.cloud.message.sendmessage.dto.MessageDataDto;
import com.ruicar.afs.cloud.message.sendmessage.dto.SendMessageDto;
import com.ruicar.afs.cloud.message.sendmessage.dto.SendResultInfoDto;
import com.ruicar.afs.cloud.message.sendmessage.service.MessageService;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * @author jiaqi.guo
 * @version 1.0
 * @created 2020/5/19 11:40
 */
@Service
@AllArgsConstructor
@Data
@Slf4j
public class MassageTemplateServiceImpl extends ServiceImpl<MessageTemplateMapper, MessageTemplate> implements MessageTemplateService {

    private CaseCustInfoService custInfoService;
    private CaseChannelInfoService caseChannelInfoService;
    private CaseCustIndividualService individualService;
    private MessageService service;
    private final MessageConfig messageConfig;

  public MessageTemplate assemblyInformation(String applyNo, String name,MessageTemplate messageTemplate) {

      String messageContent = messageTemplate.getTemplateContent();
      String applySex="";//主借人性别
      String commonSex="";//共借人性别
      String guarantorSex="";//担保人性别
      String applyName="";//主借人名称
      String commonName="";//共借人姓名
      String guarantorName="";//担保人姓名
      List<CaseCustInfo> custInfoList = custInfoService.list(Wrappers.<CaseCustInfo>query().lambda()
              .eq(CaseCustInfo::getApplyNo, applyNo));
      if(CollectionUtil.isNotEmpty(custInfoList)){
          for(CaseCustInfo custInfo:custInfoList){
              if(CustRoleEnum.MIANCUST.getCode().equals(custInfo.getCustRole())){
                  applyName=custInfo.getCustName();
                  CaseCustIndividual custIndividual = individualService.getOne(Wrappers.<CaseCustIndividual>query().lambda()
                          .eq(CaseCustIndividual::getCustId, custInfo.getId()));
                  if(ObjectUtils.isNotEmpty(custIndividual)){
                      applySex=custIndividual.getSex();
                  }
              }
              if(CustRoleEnum.COMMONCSUT.getCode().equals(custInfo.getCustRole())){
                  commonName=custInfo.getCustName();
                  CaseCustIndividual custIndividual = individualService.getOne(Wrappers.<CaseCustIndividual>query().lambda()
                          .eq(CaseCustIndividual::getCustId, custInfo.getId()));
                  if(ObjectUtils.isNotEmpty(custIndividual)){
                      commonSex=custIndividual.getSex();
                  }
              }
              if(CustRoleEnum.GUARANTOR.getCode().equals(custInfo.getCustRole())){
                  guarantorName=custInfo.getCustName();
                  CaseCustIndividual custIndividual = individualService.getOne(Wrappers.<CaseCustIndividual>query().lambda()
                          .eq(CaseCustIndividual::getCustId, custInfo.getId()));
                  if(ObjectUtils.isNotEmpty(custIndividual)){
                      guarantorSex=custIndividual.getSex();
                  }
              }

          }
      }
      if (TemplateTypeEnum.APPLYP.getCode().equals(messageTemplate.getTemplateType())
              ||TemplateTypeEnum.COMMON.getCode().equals(messageTemplate.getTemplateType())
              ||TemplateTypeEnum.GUARANTOR.getCode().equals(messageTemplate.getTemplateType())) {
          if (ObjectUtils.isNotEmpty(messageTemplate)) {
              log.info("*****************开始获取模板信息Start*****************");
              //*Name:*姓名  性别称呼:genderName 先生/女士
              if(TemplateTypeEnum.APPLYP.getCode().equals(messageTemplate.getTemplateType())){
                  messageContent = messageContent.replace("[applyName]",applyName);
              }
              else if(TemplateTypeEnum.COMMON.getCode().equals(messageTemplate.getTemplateType())){
                  messageContent = messageContent.replace("[commonName]",commonName);
              }
              else if(TemplateTypeEnum.GUARANTOR.getCode().equals(messageTemplate.getTemplateType())){
                  messageContent = messageContent.replace("[guarantorName]",guarantorName);
              }
              if (AfsEnumUtil.key(SexEnum.man).equals(applySex)) {
                  messageContent = messageContent.replace("[applySex]", "先生");
              } else {
                  messageContent = messageContent.replace("[applySex]", "女士");
              }
              if (AfsEnumUtil.key(SexEnum.man).equals(commonSex)) {
                  messageContent = messageContent.replace("[commonSex]", "先生");
              } else {
                  messageContent = messageContent.replace("[commonSex]", "女士");
              }
              if (AfsEnumUtil.key(SexEnum.man).equals(guarantorSex)) {
                  messageContent = messageContent.replace("[guarantorSex]", "先生");
              } else {
                  messageContent = messageContent.replace("[guarantorSex]", "女士");
              }
              log.info("*****************开始获取模板信息End*****************");
          }
      }
      else if (TemplateTypeEnum.APPROVE.getCode().equals(messageTemplate.getTemplateType())) {
          if (ObjectUtils.isNotEmpty(messageTemplate)) {
              CaseChannelInfo caseChannelInfo = caseChannelInfoService.getOne(Wrappers.<CaseChannelInfo>query().lambda()
                      .eq(CaseChannelInfo::getApplyNo, applyNo));
              if(ObjectUtils.isNotEmpty(caseChannelInfo)){
                  log.info("*****************开始获取信贷专员模板信息Start*****************");
                  messageContent = messageContent.replace("[applyNo]", applyNo);
                  messageContent = messageContent.replace("[applyName]", applyName);
                  messageContent = messageContent.replace("[saleAdvisor]", caseChannelInfo.getSaleAdvisor());
                  log.info("*****************开始获取信贷专员模板信息End*******************");

              }else{
                  throw new AfsBaseException("信贷专员信息不存在");
              }
          }
      }
      else if (TemplateTypeEnum.SPOUSE.getCode().equals(messageTemplate.getTemplateType())) {
          if (ObjectUtils.isNotEmpty(messageTemplate)) {
              if(!StringUtils.isEmpty(name)){
                  log.info("*****************开始获取配偶模板信息Start*****************");
                  messageContent = messageContent.replace("[spouseName]", name.substring(0,1));
                  log.info("*****************开始获取配偶模板信息End*******************");
              }else{
                  throw new AfsBaseException("其他联系姓名错误:"+name);
              }

          }
      }
      else if (TemplateTypeEnum.OTHER.getCode().equals(messageTemplate.getTemplateType())) {
          if (ObjectUtils.isNotEmpty(messageTemplate)) {
              if(!StringUtils.isEmpty(name)){
                  log.info("*****************开始获取信其他联系人模板信息Start*****************");
                  messageContent = messageContent.replace("[otherName]", name.substring(0,1));
                  messageContent = messageContent.replace("[applyName]", applyName);
                  log.info("*****************开始获取其他联系人模板信息End*******************");
              }else{
                  throw new AfsBaseException("其他联系姓名错误:"+name);
              }

          }
      }
      log.info("组装后短信内容:,{}",messageContent);
      messageTemplate.setTemplateContent(messageContent);
      return messageTemplate;
  }
  /**
   * @description: 审批核准时短信发送
   * @author jiaqi.guo
   * @created 2020/9/8 18:45
   * @version 1.0
   */
  public void sendInformation(String applyNo,String templateType){
      //查询生效模板
      MessageTemplate messageTemplate = this.getOne(Wrappers.<MessageTemplate>query().lambda()
              .eq(MessageTemplate::getTemplateType,templateType)
              .eq(MessageTemplate::getStatus,WhetherEnum.YES.getCode()));
      if (ObjectUtils.isNotEmpty(messageTemplate)) {
          List list=  this.updateInformation(applyNo,messageTemplate);
          if(list.size()>1){
              if(ObjectUtils.isNotEmpty(list.get(1))){
                  MessageTemplate newMessage=(MessageTemplate) list.get(1);
                  SendMessageDto messageDto= new SendMessageDto();
                  messageDto.setChannel(messageTemplate.getChannel());
                  messageDto.setCode(messageConfig.getCode());
                  messageDto.setTimestamp(System.currentTimeMillis()/1000+"");
                  messageDto.setUid(messageConfig.getUid());

                  List<MessageDataDto> dataDtoList=new ArrayList<>();
                  MessageDataDto dataDto= new MessageDataDto();
                  dataDto.setDeptId(messageConfig.getDeptId());
                  dataDto.setOrigin(messageConfig.getOrigin());
                  dataDto.setPhone(list.get(0).toString());
                  //estimatedTime不传默认当晚上23:59失效
                  /*   dataDto.setEstimatedTime();*/
                  //防重复-一天重复发
                  SimpleDateFormat sd=new SimpleDateFormat("yyyyMMdd");
                  dataDto.setSummaryId(applyNo+list.get(0).toString()+sd.format(new Date()));
                  dataDto.setSmsContent(newMessage.getTemplateContent());
                  dataDto.setTemplateId(newMessage.getTemplateId());
                  dataDto.setPriority(newMessage.getPriority());
                  dataDtoList.add(dataDto);

                  messageDto.setMessageDataDto(dataDtoList);
                  SendResultInfoDto sendResultInfoDto=service.sendMessageData(messageDto);
                  if(ObjectUtils.isNotEmpty(sendResultInfoDto)){
                      if(sendResultInfoDto.getResult().equals(ResultBooleanEnum.TRUE.getCode())){
                          log.info("短信发送成功");
                      }
                      else{
                          log.info("模板ID为:" + templateType + "发送失败！原因:"+sendResultInfoDto.getMsgInfo());
                      }
                  }else{
                      log.info("短信接口响应失败！");
                  }
              }
          }
      }else{
          log.info("短信模板不存在！");

      }
      log.info("短信发送成功！");
  }
  /**
   * @description: 获取审批模板
   * @author jiaqi.guo
   * @created 2020/9/8 19:20
   * @version 1.0
   */
  private List updateInformation(String applyNo,MessageTemplate messageTemplate ) {
      String messageContent = "";
      /**客户姓名*/
      String applyName = "";
      /**客户性别*/
      String applySex = "";
      /**手机号码*/
      String phone="";
      List list=new ArrayList();
      List<CaseCustInfo> custInfoList = custInfoService.list(Wrappers.<CaseCustInfo>query().lambda().eq(CaseCustInfo::getApplyNo, applyNo));
      for (CaseCustInfo custInfo : custInfoList) {
          if (CustRoleEnum.MIANCUST.getCode().equals(custInfo.getCustRole())) {
              CaseCustIndividual custIndividual = individualService.getOne(Wrappers.<CaseCustIndividual>query().lambda()
                      .eq(CaseCustIndividual::getCustId, custInfo.getId()));
              if (ObjectUtils.isNotEmpty(custIndividual)) {
                  applySex = custIndividual.getSex();
              }
              phone=custInfo.getTelPhone();
              applyName = custInfo.getCustName();
          }
      }
      /**审批专员*/
      if (TemplateTypeEnum.APPROVE_PERSON.getCode().equals(messageTemplate.getTemplateType())) {
          if (ObjectUtils.isNotEmpty(messageTemplate)) {
              CaseChannelInfo caseChannelInfo = caseChannelInfoService.getOne(Wrappers.<CaseChannelInfo>query().lambda()
                      .eq(CaseChannelInfo::getApplyNo, applyNo));
              if (ObjectUtils.isNotEmpty(caseChannelInfo)) {
                  log.info("*****************开始获取信贷专员模板信息Start*****************");
                  phone=caseChannelInfo.getSalePhone();
                  messageContent = messageContent.replace("[applyNo]", applyNo);
                  messageContent = messageContent.replace("[applyName]", applyName);
                  log.info("*****************开始获取信贷专员模板信息End*******************");

              } else {
                  log.info("信贷专员信息不存在");
              }
          }
          log.info("审批结果信贷专员组装后短信内容:,{}", messageContent);
      }
      else if (TemplateTypeEnum.APPROVE_MUSTER.getCode().equals(messageTemplate.getTemplateType())) {
          if (CollectionUtil.isNotEmpty(custInfoList)) {
              messageContent = messageContent.replace("[applyNo]", applyNo);
              messageContent = messageContent.replace("[applyName]", applyName);
              if (AfsEnumUtil.key(SexEnum.man).equals(applySex)) {
                  messageContent = messageContent.replace("[applySex]", "先生");
              } else {
                  messageContent = messageContent.replace("[applySex]", "女士");
              }

          }

      }
      messageTemplate.setTemplateContent(messageContent);
      list.add(phone);
      list.add(messageTemplate);
      return list;
  }
}
